<!-- 下拉选择控件 -->
<template>
  <a-select
    v-if="!area && !nation && !department && !humanRoster && !probation"
    v-model="modelValue"
    :options="copyProps.selectOptions"
    :field-names="fieldNames"
    :disabled="disabled"
    @change="change"
  >
  </a-select>
  <a-cascader
    v-else-if="area"
    :options="areaData.data"
    :disabled="disabled"
    :field-names="areafieldNames"
    v-model="modelValue"
  />
  <a-select
    v-else-if="nation"
    v-model="modelValue"
    :options="nationData.data"
    :field-names="nationfieldNames"
    :disabled="disabled"
    @change="change"
  >
  </a-select>
  <a-tree-select
    v-else-if="department"
    :disabled="disabled"
    @change="change"
    :fieldNames="{
      key: 'id',
      title: 'name'
    }"
    :data="copyProps.selectOptions"
    v-model="modelValue"
    placeholder="请选择"
  ></a-tree-select>
  <a-select
    v-else-if="humanRoster"
    placeholder="请选择"
    v-model="modelValue"
    :popup-visible="false"
    allow-search
    allow-clear
    :disabled="disabled"
    @popup-visible-change="showHumanModal"
    :multiple="isMultiple"
  >
    <a-option
      v-for="item in list.humanList"
      :label="item.name"
      :value="item.id"
      :key="item.id"
    ></a-option>
  </a-select>
  <a-select
    v-else-if="probation"
    v-model="modelValue"
    :field-names="fieldNames"
    :options="copyProps.selectOptions"
    :disabled="disabled"
    @change="change"
  >
    <template #label="{ data }">
      <span> {{ data.label }}个月 </span>
    </template>
  </a-select>

  <!-- <a-select
    v-else-if="immediateSuperior"
    placeholder="请选择"
    v-model="modelValue"
    allow-search
    allow-clear
    :disabled="disabled"
    @popup-visible-change="showImmediateSuperiorModal"
  >
    <a-option
      v-for="item in list.humanList"
      :label="item.name"
      :value="item.id"
      :key="item.id"
    ></a-option>
  </a-select> -->

  <HumanRosterModal
    style="z-index: 9999"
    v-model:visible="humanModalVisible"
    @humanRosterEmit="humanRosterEmit"
    :rowSelectionType="rowSelection"
  ></HumanRosterModal>

  <!-- <ImmediateSuperiorModal
    style="z-index: 9999"
    v-model:visible="immediateSuperiorModalVisible"
    @immediateSuperiorEmit="immediateSuperiorEmit"
  ></ImmediateSuperiorModal> -->
</template>

<script lang="ts" setup>
import areaDataThree from '@/assets/json/pca-code.json';
import areaDataTwo from '@/assets/json/pc-code.json';
import nationality from '@/assets/json/nation.json';
import {
  getDataResourcesValue,
  getDataResourcesById
} from '@/apis/controltotal/index';
import clonedeep from 'lodash.clonedeep';
import { isJSON } from '@/utils/isType';
import mitter from '@/utils/mitt';
import { isArray } from 'lodash';
import { getAllHumanRoster } from '@/utils/common';
import useControlValuesStore from '@/store/controlValues';

const controlValuesStore = useControlValuesStore();
const props = withDefaults(
  defineProps<{
    props: { [propName: string]: any };
    name?: string;
    code?: string;
    required?: boolean;
    oneValue: any;
    disabled?: boolean;
    selectOptions?: any[];
    regex?: {
      [name: string]: {
        role: any;
        name: any;
      };
    };
  }>(),
  {
    selectOptions: () => []
  }
);

watch(
  () => props.selectOptions,
  (val) => {
    if (!val) return;
    copyProps.value.selectOptions = clonedeep(val);
  }
);

const areaData: any = reactive({ data: [] });
const nationData: any = reactive({ data: [] });
const area = ref(true); //地区
const nation = ref(true); // 民族
const department = ref(true); // 部门 or 树
const humanRoster = ref(true); // 组织负责人 | 分管领导
const probation = ref(true); // 试用期
const immediateSuperior = ref(true); // 直接上级
const nationfieldNames = { value: 'id', label: 'name' };
const areafieldNames = { value: 'code', label: 'name' };
const areaDataShow = (code: any) => {
  if (
    code === 'CF058C6BF648940BA96B49495CC768E20' ||
    code === 'CC878E7B5A1CF439983F8BDED23D5C3C4'
  ) {
    areaData.data = areaDataTwo;
  } else if (code === 'C02BE308AEE674E3F95335AED60682954') {
    areaData.data = areaDataThree;
  } else {
    area.value = false;
  }
};
const nationShow = (code: any) => {
  if (code === 'C801D4E720AB54DADAB310FFE9A544135') {
    nationData.data = nationality.data;
  } else {
    nation.value = false;
  }
};
const departmentShow = (code: any) => {
  if (
    code === 'CED44AC9966904CD1AB546D309903727C' ||
    code === 'C65B19139CD80411DB6B20F2E10CFDE9F' ||
    code === 'C073F4F41C46D4CA3AF3BEC1F51A8F410'
  ) {
    // nationData.data = nationality.data;
  } else {
    department.value = false;
  }
};

let list: any = reactive({
  humanList: []
});

// 显示人员弹框是否单选还是多选
let rowSelection = reactive({
  type: 'radio'
});

let isMultiple = ref(false); // 选择器是否多选

const humanRosterShow = async (code: string) => {
  // 如果控件是组织负责人、分管领导、直接上级
  if (
    code === 'CB0C63F38283045F58FFF1B1EABE5D151' ||
    code === 'CA6BD9CC1C99D4D13AD4F5009EF4F9586' ||
    code === 'C2276E2F73E8D4DAF9160F61B2C8BCEBA'
  ) {
    list.humanList = await getAllHumanRoster();
  } else {
    humanRoster.value = false;
  }
  if (code === 'CA6BD9CC1C99D4D13AD4F5009EF4F9586') {
    rowSelection.type = 'checkbox';
    rowSelection.showCheckedAll = true;
    isMultiple.value = true;
  } else {
    isMultiple.value = false;
  }
};

let humanModalVisible = ref(false);
// 显示人员花名册弹框
const showHumanModal = () => {
  humanModalVisible.value = true;
};

let humanName = ref('');
const humanRosterEmit = (record: any) => {
  // 多选
  if (record?.length) {
    modelValue.value = record.map((el: any) => el.id);
  }
  //单选
  else {
    // humanName.value = record.name;
    modelValue.value = record.id;
  }
};

// const immediateSuperiorShow = async (code: string) => {
//   // 如果控件是组织负责人、分管领导
//   if (code === 'CECEBAA743F9B4160B40A5A3E78588712') {
//     list.humanList = await getAllHumanRoster();
//     //
//   } else {
//     immediateSuperior.value = false;
//   }
// };

// let immediateSuperiorModalVisible = ref(false);

// // 显示直接上级弹框
// const showImmediateSuperiorModal = () => {
//   immediateSuperiorModalVisible.value = true;
// };

// const immediateSuperiorEmit = (record: any) => {
//   humanName.value = record.name;
//   modelValue.value = record.id;
// };

const probationShow = (code: string) => {
  if (code === 'CCDE5F027E72F4B00A891F2DA946A0532') {
    probation.value = true;
  } else {
    probation.value = false;
  }
};

const init = () => {
  areaDataShow(props.code);
  nationShow(props.code);
  departmentShow(props.code);
  humanRosterShow(props.code as string);
  probationShow(props.code as string);
  // immediateSuperiorShow(props.code as string);
};
init();
const emit = defineEmits(['update:oneValue']);
const modelValue = computed({
  get: () => {
    if (props.code === 'CA6BD9CC1C99D4D13AD4F5009EF4F9586') {
      let temp;
      if (typeof props.oneValue === 'string') {
        temp = props.oneValue?.split(',').map((ele: any) => {
          return Number(ele);
        });
      } else {
        temp = props.oneValue;
      }

      return temp;
    }
    if (!props.oneValue) return void 0;
    if (props.props.keyType === 1) return props.oneValue;

    return Number(props.oneValue);
  },
  set: (val) => {
    emit('update:oneValue', val);
  }
});
const fieldNames = reactive({ value: 'value', label: 'label' });
const dataResources = reactive<any>({ detail: {} });
//复制一份props
const copyProps: any = ref();
const getProps = async () => {
  let differentPorts;
  copyProps.value = clonedeep(props.props);
  if (isJSON(copyProps.value)) {
    copyProps.value = JSON.parse(copyProps.value);
  }
  if (copyProps.value.dataResourcesId) {
    fieldNames.value = 'id';
    fieldNames.label = 'name';
    //获取数据来源详细信息
    let res = await getDataResourcesById(copyProps.value.dataResourcesId);
    dataResources.detail = clonedeep(res.dataResourcesDetail) || {};
    dataResources.detail.copyParams = {};
    res.dataResourcesDetail.params.forEach((item: any) => {
      if (item.paramValueWay === 2) {
        // 如果是关联控件，查询对应控件的值作为当前控件的参数
        // pinia查找记录每个控件的值
        const parent = controlValuesStore.data?.find(
          (ctl) => ctl.ctlCode === item.paramValue
        );

        dataResources.detail.copyParams[item.paramName] = parent?.ctlValue;
      } else {
        //非关联控件
        dataResources.detail.copyParams[item.paramName] = getValueByDataType(
          item.paramValue,
          item.paramDataType
        );
      }
    });
    getDataResources(
      dataResources.detail.url,
      'get',
      dataResources.detail.copyParams,
      differentPorts
    );
  }
};
// 根据数据类型，进行转换成接口需要的数据类型
const getValueByDataType = (paramsValue: any, paramsType: number) => {
  // if (!paramsType) return void 0;
  // dataType 1小数数组2整数数组3字符串数组4小数5整数6字符串
  switch (paramsType) {
    case 1:
      return paramsValue?.join(',');
    case 2:
      return paramsValue?.join(',');
    case 3:
      return paramsValue?.join(',');
    case 4:
      return Number(paramsValue);
    case 5:
      return Number(paramsValue);
    case 6:
      return paramsValue;
  }
};
watchEffect(() => {
  getProps();
});

//获取下拉数据
const getDataResources = async (
  url: string,
  method: 'post' | 'get',
  params: any,
  differentPorts?: number,
  onChange?: boolean
) => {
  try {
    let resData = await getDataResourcesValue({
      url: url,
      method: method,
      params,
      differentPorts
    });
    copyProps.value.selectOptions = [];

    const kesArr = Object.keys(resData);
    const tempData =
      kesArr.indexOf('content') !== -1 ? resData.content : resData;
    copyProps.value.selectOptions =
      typeof tempData === 'object' && tempData !== null ? tempData : null;
    // if (tempData === null) {
    //   emit('update:oneValue', null);
    // }
    onChange ? emit('update:oneValue', null) : null;

    // 部门的code
    if (props.code === 'CED44AC9966904CD1AB546D309903727C') {
      copyProps.value.selectOptions = changeDepartmentData(
        copyProps.value.selectOptions
      );
    }
    // 职位类别code
    else if (props.code === 'C63EC32DCE9CC4BE6AC7649E23234A542') {
      department.value = true;
      copyProps.value.selectOptions =
        copyProps.value.selectOptions.positionCategoryList;
    }
    if (!Array.isArray(copyProps.value.selectOptions)) {
      copyProps.value.selectOptions = [];
    }
    // change(modelValue.value);
  } catch (error) {
    console.log(111, error);
  }
};

// 选项改变通知联动控件
const change = (value: any) => {
  const obj = { code: props.code, value: value };
  mitter.emit('selectChange', obj);
};

// 联动控件接收信息
mitter.on('selectChange', (res: any) => {
  if (!isArray(dataResources.detail.params)) return;
  dataResources.detail.params.forEach((item: any) => {
    if (res.code && res.code === item.paramValue) {
      dataResources.detail.copyParams[item.paramName] = res.value;
      getDataResources(
        dataResources.detail.url,
        'get',
        dataResources.detail.copyParams,
        dataResources.detail.copyParams?.differentPorts,
        true
      );
      change(undefined); //获取数据后，选择值设为空
      return;
    }
  });
});

// 处理部门数据
const changeDepartmentData = (data: any) => {
  let newData = clonedeep(data);
  newData = newData.map((ele: any) => {
    return changeDepartment(ele);
  });

  return newData;
};
// 处理部门树形结构
const changeDepartment = (data: any) => {
  const newData = clonedeep(data);
  if (newData.typeId === 1) {
    newData.selectable = false;
  } else {
    newData.selectable = true;
  }
  if (newData.children) {
    newData.children = newData.children.map((ele: any) => {
      return changeDepartment(ele);
    });
  }
  return newData;
};
onBeforeUnmount(() => {
  mitter.off('selectChange');
});
</script>

<style scoped lang="less"></style>
